package com.zch.book.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zch.book.service.UserService;
import com.zch.book.service.impl.UserServiceImpl;



/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    UserService us = new UserServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得操作标记
		String flag = request.getParameter("flag");
		if("doOut".equals(flag)){
			doOut(request, response);
		}else if("login".equals(flag)){
			doLogin(request, response);
		}
	}

	
	/**
	 * 注销功能的实现
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得session对象
		HttpSession session = request.getSession();
		//失效---session中存的值
		session.invalidate();
		//重定向回登陆页面
		response.sendRedirect("login.jsp");
	}
	
	/**
	 * 用户登录信息判断
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得用户名
		String name = request.getParameter("userName");
		//获得密码
		String pwd = request.getParameter("pwd");
		// 获得session对象
		HttpSession session = request.getSession();
		//获得登录判断的集合对象
		Map<String, Object> map = us.login(name, pwd);
		// 判断登录是否成功
		boolean isLogin = (Boolean) map.get("isLogin");
		System.out.println(isLogin);
		if (isLogin) {
			// 登录成功,session域中存放用户对象
			session.setAttribute("user1", map.get("user1"));
			response.sendRedirect("BookServlet?method=getAllBook");
		} else {
			// 登录失败
			request.setAttribute("errorMsg", map.get("errorMsg"));
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}